<template lang="">
    <div>
      <el-switch
        v-model="draggable"
        active-text="开启拖拽"
        inactive-text="关闭拖拽">
      </el-switch>
      <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
      <el-button type="danger" round @click="batchDelete">批量删除</el-button>
        <el-tree 
        :data="menus"
        show-checkbox
        node-key="catId"
        :props="defaultProps"
        :default-expanded-keys="expandedKey"
        :draggable="draggable"
        :allow-drop="allowDrop"
        @node-drop="handleDrop"
        ref="menuTree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span>
            <el-button
              v-if="node.level <= 2"
              type="text"
              size="mini"
              @click="() => append(data)">
              Append
            </el-button>
            <el-button
              v-if="node.childNodes.length == 0"
              type="text"
              size="mini"
              @click="() => remove(node, data)">
              Delete
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => modify(data)">
              Modify
            </el-button>
          </span>
          </span>
        </el-tree>

        <el-dialog
          :title="title"
          :visible.sync="dialogVisible"
          width="30%"
          :closeOnClickModal="false"
         >
          <el-form :model="category" ref="category">
            <el-form-item label="分类名称">
              <el-input v-model="category.name" autocomplete="off"></el-input>
            </el-form-item>
             <el-form-item label="图标">
              <el-input v-model="category.icon" autocomplete="off"></el-input>
            </el-form-item>
             <el-form-item label="计量单位">
              <el-input v-model="category.productUnit" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitData">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data() {
    return {
      pcid: [],
      draggable: false,
      updateNode: [],
      maxLevel: 0,
      title: "",
      dialogType: "",
      category: {
        name: "",
        icon: "",
        productUnit: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
      },
      expandedKey: [],
      menus: [],
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  methods: {
    batchSave() {
      // 层级
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNode, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success("菜单顺序修改成功");
          this.getMenus();
          // 展开菜单
          this.expandedKey = this.pcid;
          this.updateNode = [];
          this.maxLevel = 0;
          // this.pcid = 0;
        }
      });
    },

    batchDelete() {
      let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, false);

      let catIds = [];
      checkedNodes.forEach((node) => {
        catIds.push(node.catId);
      });

      this.$confirm(`是否批量【${catIds}】删除?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log("删除成功");
              this.getMenus();

              // 展开菜单
            
            }
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      console.log(catIds);
    },

    allowDrop(draggingNode, dropNode, type) {
      // 被拖动的当前节点的总层数和父节点的总层数不能大于三
      this.countNodeLevel(draggingNode);
      // 解决BUG，原因，要将maxLevel=0还原为默认值
      let deep =
        this.maxLevel - draggingNode.level + 1 < 0
          ? 1
          : this.maxLevel - draggingNode.level + 1;
      console.log("被拖拽的节点：", draggingNode);
      console.log("deep", deep);
      this.maxLevel = 0;
      if (type === "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      let pcid;
      let siblings = null;
      // 父id
      if (dropType === "before" || dropType === "after") {
        pcid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pcid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }

      this.pcid.push(pcid);
      // 顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId === draggingNode.data.catId) {
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            // 修改子节点的层级
            this.modifyChildLevel(siblings[i]);
          }

          // 修改被拖拽的节点的父id
          this.updateNode.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pcid,
            catLevel: catLevel,
          });
        } else {
          this.updateNode.push({
            catId: siblings[i].data.catId,
            sort: i,
          });
        }
      }
    },

    modifyChildLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (const children of node.childNodes) {
          let cNode = children.data;
          cNode.catLevel = children.level;
          this.updateNode.push({
            catId: cNode.catId,
            catLevel: cNode.catLevel,
          });
          this.modifyChildLevel(cNode);
        }
      }
    },

    countNodeLevel(draggingNode) {
      // 找到子节点的最大深度
      if (
        draggingNode.childNodes != null &&
        draggingNode.childNodes.length > 0
      ) {
        for (const node of draggingNode.childNodes) {
          if (node.level > this.maxLevel) {
            this.maxLevel = node.level;
            this.countNodeLevel(node);
            break;
          }
        }
      } else {
        // this.maxLevel = 0;
      }
    },

    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },

    append(data) {
      (this.dialogType = "add"), (this.title = "添加分类");
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.showStatus = 1;
      this.category.name = "";
      this.category.catId = null;
      this.category.icon = "";
      this.category.productUnit = "";
    },

    remove(node, data) {
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log("删除成功");
              this.getMenus();

              // 展开菜单
              this.expandedKey = [node.parent.data.catId];
            }
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    modify(data) {
      this.dialogType = "edit";
      this.title = "修改分类";
      this.dialogVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category.name = data.category.name;
        this.category.catId = data.category.catId;
        this.category.icon = data.category.icon;
        this.category.productUnit = data.category.productUnit;
        this.category.parentCid = data.category.parentCid;
      });
    },

    submitData() {
      if (this.dialogType === "add") {
        this.addCategory();
      } else if (this.dialogType === "edit") {
        this.modifyCategory();
      }
    },

    addCategory() {
      console.log(this.category);

      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success("菜单修改成功");
          this.$nextTick(() => {
            this.$refs["category"].resetFields();
          });
          this.category.name = "";
          this.category.catId = null;
          this.category.icon = "";
          this.category.productUnit = "";
          this.dialogVisible = false;
          this.getMenus();
          // 展开菜单
          this.expandedKey = [this.category.parentCid];
        }
      });
    },

    modifyCategory() {
      let { catId, name, icon, productUnit } = this.category;

      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success("菜单修改成功");
          this.$nextTick(() => {
            this.$refs["category"].resetFields();
          });
          this.dialogVisible = false;
          this.category.name = "";
          this.category.catId = null;
          this.category.icon = "";
          this.category.productUnit = "";
          this.getMenus();
          // 展开菜单
          this.expandedKey = [this.category.parentCid];
        }
      });
    },
  },
  created() {
    this.getMenus();
  },
};
</script>
<style lang="">
</style>